<template>
    <section class="add" style="margin-top: 30px;">
        <el-form ref="formData"
                :rules="rules" 
                :model="formData" 
                label-width="150px">
            <el-form-item label="考试名称"
                          prop="examName">
                <el-input v-model="formData.examName" style="width: 500px"></el-input>
            </el-form-item>
            <el-form-item label="老师信息" v-if="type == 0"
                          prop="teacherId">
              <el-select v-model="formData.teacherId" clearable placeholder="请选择老师信息">
                            <el-option
                              v-for="item in teacherIdOptions"
                              :key="item.key"
                              :label="item.value"
                              :value="item.key"
                            >
                            </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="考试时长" prop="examDuration">
              <el-input 
                v-model="formData.examDuration" 
                style="width: 400px"
                placeholder="请输入考试时长（分钟）">
              </el-input>
              <span style="margin-left: 8px; color: #999;">分钟</span>
          </el-form-item>
            <el-form-item label="考试截止日期" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                type="datetime"
                placeholder="选择考试截止日期"
                style="width: 500px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="考试封面"
                          prop="examavatar"
            >
              <uploadImg v-model="formData.examavatar"></uploadImg>
            </el-form-item>
            <el-form-item label="考试备注"
                          prop="remark">
                <el-input v-model="formData.remark" style="width: 500px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('formData')">确 定</el-button>
              <el-button @click="cancle()">取 消</el-button>
            </el-form-item>
        </el-form>
    </section>
</template>

<script>
import { getList, insert, update, get, del, getTeacherDate } from '@/api/Exam/index'
import Pagination from '@/components/Pagination'
import { tableUtil } from '@/mixins/table'
import { Message } from 'element-ui'
import uploadImg from '@/components/ImageUpload'
import ImgPreview from '@/components/ImgPreview'

export default {
  mixins: [tableUtil],
  components: {
    Pagination, uploadImg, ImgPreview
  },
  data() {
    return {
      type: localStorage.getItem('examType'),
      listQueryParam: {
        current: 1,
        pageSize: 5
      },
      currentId: 0,
      showEcharts: false,
      formData: {},
      rules: {
        examName: [
          { required: true, message: '请输入考试名称', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '请选择老师信息', trigger: 'change' }
        ],
        examDuration: [
          { required: true, message: '请选择考试时长', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择考试截止日期', trigger: 'change' }
        ],
        examavatar: [
          { required: true, message: '请选择考试截止日期', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入考试备注', trigger: 'blur' }
        ]
      },
      teacherIdOptions: []
    }
  },
  mounted() {
    this.getTableDataList()
    this.getTeacherDateList()
  },
  methods: {
    showEcharts1(row) {
      this.currentId = row.id
      this.$router.push('/echarts/index/' + this.currentId)
    },
    getTableDataList() {
      if (this.type == 1) {
        this.listQueryParam.teacherId = localStorage.getItem('examId')
      }
      getList(this.listQueryParam).then((res) => {
        this.total = res.data.total
        this.tableData = res.data.records
      })
    },
    updateClick(row) {
      this.dialogTitle = '修改'
      get(row.id).then((res) => {
        this.formData = res.data
        this.addOrUpdateDialogVisible = true
      })
    },
    delByIds(ids) {
      del(ids).then((res) => {
        Message.success('删除成功')
        this.getTableDataList()
      })
    },
    saveData() {
      console.log('考试封面',this.formData.examavatar)
      if (this.type == 1) {
        this.formData.teacherId = localStorage.getItem('examId')
      }

      if (!this.isPositiveInteger(Number(this.formData.examDuration))) {
        Message.error('考试时长必须是正整数的分钟数');
        return; // 如果不是正整数，终止保存操作
      }

      // 格式化截止日期和时间
      if (this.formData.endTime) {
        this.formData.endTime = this.formatDate(this.formData.endTime)
      }
      if (this.formData.id) {
        update(this.formData).then((res) => {
          Message.success('修改成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      } else {
        insert(this.formData).then((res) => {
          Message.success('添加成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
          // 跳转到目标页面
          this.$router.push('/Exam/query')
        })
      }
    },
    isPositiveInteger(value) {
      // 检查是否为正整数
      return Number.isInteger(value) && value > 0;
    },
    getTeacherDateList() {
      getTeacherDate().then(res => {
        this.teacherIdOptions = res.data
      })
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    cancle(){
        this.formData={};
    }
  }
}
</script>
